﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace BSPortal.Usercontrol.Admin.Book.ListBook
{
    public partial class frmListBook : System.Web.UI.Page
    {
        
        private short id = 0;
        private MainService service = new MainService();
        private static string fileNameImage = string.Empty;
        public string publisherName = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }



        private void LoadData()
        {
            string str = Request["ProductId"];
            short line = short.Parse(Request["Line"]!=null? Request["Line"]:"0");
            switch (line)
            {
                case 1:
                    publisherName = ResourceString.PublisherNameBook;
                    trWriter.Visible = true;
                    trTechnicInfo.Visible = false;
                    break;
                case 2:
                    publisherName = ResourceString.PublisherNameElectronic;
                    tdImage.RowSpan = 7;
                    tdImage2.RowSpan = 7;
                    trWriter.Visible = false;
                    break;
                case 3:
                    publisherName = ResourceString.PublisherNameElectronic;
                    tdImage.RowSpan = 7;
                    tdImage2.RowSpan = 7;
                    trWriter.Visible = false;
                    break;
                default:
                    trWriter.Visible = true;
                    publisherName = ResourceString.PublisherNameBook;
                    break;
            }
            var categoryData = service.GetListSecondLevelCategory(line);
            ddlCategory.DataSource = categoryData;
            ddlCategory.DataTextField = "Name";
            ddlCategory.DataValueField = "CategoryId";
            ddlCategory.DataBind();
            if (str == null)
            {
                var listAuthor = service.GetAllWriter();
                ddlAuthor.DataSource = listAuthor;
                ddlAuthor.DataTextField = "Name";
                ddlAuthor.DataValueField = "WriterId";
                ddlAuthor.DataBind();
                var listPublisher = service.GetListPublisherByCategory(line);
                ddlPublishName.DataSource = listPublisher;
                ddlPublishName.DataTextField = "Name";
                ddlPublishName.DataValueField = "PublisherId";
                ddlPublishName.DataBind();
            }
            else
            {
                id = short.Parse(str);
                var data = service.GetProductById(short.Parse(str));
                if (data != null)
                {
                    txtId.Text = data.ProductId.ToString();
                    txtName.Text = data.Name;
                    ddlCategory.SelectedValue = data.CategoryId.ToString();
                    txtPrice.Text = data.Price.ToString();
                    previewImage.ImageUrl = "~/images/" + data.Image;
                    fileNameImage = data.Image;
                    reContent.Content = data.Content;
                    txtDistributor.Text = data.Distributor;
                    var listAuthor = service.GetAllWriter();
                    ddlAuthor.DataSource = listAuthor;
                    ddlAuthor.DataTextField = "Name";
                    ddlAuthor.DataValueField = "WriterId";
                    ddlAuthor.DataBind();

                    if (line == 1)
                        ddlAuthor.SelectedValue = data.WriterId.Value.ToString();                    

                    var listPublisher = service.GetListPublisherByCategory(line);
                    ddlPublishName.DataSource = listPublisher;
                    ddlPublishName.DataTextField = "Name";
                    ddlPublishName.DataValueField = "PublisherId";
                    ddlPublishName.DataBind();
                    ddlPublishName.SelectedValue = data.PublisherId.Value.ToString();
                    txtDiscount.Text = (data.Discount * 100).ToString();
                    txtfee.Text = data.Tranformfee.ToString();
                    reTechnicInfo.Content = data.TechnicInfo;
                    chkIsPublished.Checked = (bool)data.IsPublished;
                }

            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (txtName.Text == "")
            {
                lblStatus.Text = "Tên không được để trống!";
                return;
            }
            short line = short.Parse(Request["Line"] != null ? Request["Line"] : "0");
            string str = Request["ProductId"];
            float discount=0;
            float.TryParse(txtDiscount.Text.Trim(), out discount);
            discount = discount/100;
            if (txtfee.Text.Trim() == "") { txtfee.Text = "0"; }
            if (str == null)
            {
                int retcode = service.CreateProduct(txtName.Text, "", reContent.Content, float.Parse(txtPrice.Text), discount, fileNameImage,
                                                    short.Parse(ddlCategory.SelectedValue),
                                                    (line ==1 )? short.Parse(ddlAuthor.SelectedValue) : (short)0,
                                                    short.Parse(ddlPublishName.SelectedValue), 10, double.Parse(txtfee.Text), reTechnicInfo.Content, chkIsPublished.Checked,txtDistributor.Text);
                previewImage.ImageUrl = "~/images/" + fileNameImage;
                hdModified.Value = "true";
                lblStatus.Text = retcode == (int) Common.RetCode.SUCESS
                                     ? "Thêm thành công..."
                                     : "Thêm không thành công...";
            }
            else
            {
                var data = service.GetProductById(short.Parse(str));
                

                int retcode = service.UpdateProduct(short.Parse(str), txtName.Text, fileNameImage, "", reContent.Content,
                                                    double.Parse(txtPrice.Text), data.Rate.Value,
                                                    short.Parse(ddlCategory.SelectedValue),
                                                    short.Parse(ddlPublishName.SelectedValue),
                                                    (line == 1) ? short.Parse(ddlAuthor.SelectedValue) : (short)0,
                                                    discount, double.Parse(txtfee.Text.ToString()),txtDistributor.Text, reTechnicInfo.Content, chkIsPublished.Checked);
                previewImage.ImageUrl = "~/images/" + fileNameImage;
                hdModified.Value = "true";
                lblStatus.Text = retcode == (int) Common.RetCode.SUCESS
                                     ? "Cập nhật thành công..."
                                     : "Cập nhật không thành công...";
            }
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            //txtName.Text = string.Empty;
            //txtPrice.Text = string.Empty;
            //ddlParentCategory.SelectedIndex = 0;
            //ddlPriceType.SelectedIndex = 0;
            //ddlCity.SelectedIndex = 0;
        }

        protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
            fileNameImage = e.filename;
            string fileName = Server.MapPath("~/") + "/images/" + e.filename;
            AsyncFileUpload1.SaveAs(fileName);
            if (AsyncFileUpload1.PostedFile != null)
            {
                HttpPostedFile file = AsyncFileUpload1.PostedFile;

                byte[] data = ReadFile(file);
                System.Web.HttpContext.Current.Session[Common.STORED_IMAGE] = data;
            }
        }

        private byte[] ReadFile(HttpPostedFile file)
        {
            byte[] data = new Byte[file.ContentLength];
            file.InputStream.Read(data, 0, file.ContentLength);
            return data;
        }
    }
}